package com.netx.generics.translation;
import java.util.Iterator;

import com.netx.generics.basic.Checker;


public class Translator {

	public static enum TRANSLATION_POLICY {
		STOP_ON_ERROR,
		STOP_ON_NULL
	}
	
	private final FirstStep<?> _firstStep;
	private TRANSLATION_POLICY _policy;
	private int _stepsPerformed;
	
	public Translator(FirstStep<?> firstStep, TRANSLATION_POLICY policy) {
		Checker.checkNull(firstStep, "firstStep");
		Checker.checkNull(policy, "policy");
		_firstStep = firstStep;
		_policy = policy;
		_stepsPerformed = 0;
	}

	public Translator(FirstStep<?> firstStep) {
		this(firstStep, TRANSLATION_POLICY.STOP_ON_ERROR);
	}

	public TRANSLATION_POLICY getTranslationPolicy() {
		return _policy;
	}
	
	public Translator setTranslationPolicy(TRANSLATION_POLICY policy) {
		Checker.checkNull(policy, "policy");
		_policy = policy;
		return this;
	}
	
	public int getTotalStepCount() {
		Iterator<TranslationStep> it = _firstStep.iterator();
		int i = 0;
		while(it.hasNext()) {
			it.next();
			i++;
		}
		return i;
	}
	
	public int getPerformedStepCount() {
		return _stepsPerformed;
	}

	public Results performWork() {
		Results r = new Results(this, _firstStep.getInitialObject());
		Iterator<TranslationStep> it = _firstStep.iterator();
		while(it.hasNext()) {
			TranslationStep step = it.next();
			r.setContents(step.performWork(r));
			_stepsPerformed++;
			if(_policy == TRANSLATION_POLICY.STOP_ON_ERROR && r.hasErrors()) {
				return r;
			}
			if(_policy == TRANSLATION_POLICY.STOP_ON_NULL && r.getContents() == null) {
				return r;
			}
		}
		return r;
	}
}
